/*
 * Web-only Vite config for building renderer as a standalone website
 */
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import AutoImport from 'unplugin-auto-import/vite'
import setupExtend from 'unplugin-vue-setup-extend-plus/vite'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  // Use renderer as the root so index.html and public/ are picked up
  root: resolve('src/renderer'),
  base: './',
  resolve: {
    alias: {
      '@renderer': resolve('src/renderer/src'),
      '~': resolve('src/renderer'),
      '@': resolve('src/renderer/src')
    },
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  },
  plugins: [
    vue(),
    AutoImport({
      imports: ['vue', 'vue-router', 'pinia'],
      eslintrc: {
        enabled: false,
        filepath: './.eslintrc-auto-import.json',
        globalsPropValue: true
      }
    }),
    setupExtend({}),
    createSvgIconsPlugin({
      iconDirs: [resolve('src/renderer/src/assets/icons/svg')],
      symbolId: 'icon-[dir]-[name]',
      svgoOptions: true
    }),
    // Static asset optimization: generate gzip files for production serving
    viteCompression({ algorithm: 'gzip', ext: '.gz', deleteOriginFile: false, threshold: 10240 })
  ],
  css: {
    postcss: {
      plugins: [
        {
          postcssPlugin: 'internal:charset-removal',
          AtRule: {
            charset: atRule => {
              if (atRule.name === 'charset') {
                atRule.remove()
              }
            }
          }
        }
      ]
    }
  },
  publicDir: resolve('src/renderer/public'),
  build: {
    // Ensure output goes to project root build_web directory
    outDir: resolve('build_web'),
    emptyOutDir: true,
    sourcemap: false,
    cssCodeSplit: true,
    minify: 'esbuild',
    assetsInlineLimit: 4096,
    rollupOptions: {
      output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: assetInfo => {
          const name = assetInfo.name ?? ''
          if (/\.(css)$/.test(name)) return 'assets/css/[name]-[hash][extname]'
          if (/\.(png|jpe?g|gif|svg|webp)$/.test(name)) return 'assets/img/[name]-[hash][extname]'
          if (/\.(ttf|otf|woff2?)$/.test(name)) return 'assets/fonts/[name]-[hash][extname]'
          return 'assets/[name]-[hash][extname]'
        }
      }
    }
  },
  // Clear, detailed logs during build
  logLevel: 'info',
  clearScreen: false
})